package com.niodata.dp.monitor.sharelib.service;

import com.niodata.dp.monitor.sharelib.entity.base.BaseResult;
import com.niodata.dp.monitor.sharelib.entity.file.FileIndexItem;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;


@Component
public class FileIndexBuildOperateService {

  @Autowired
  private RestTemplate restTemplate;

  @Value("${monitor.server.address}")
  private String server;
  @Value("${monitor.server.port}")
  private String port;

  public BaseResult startFileIndexBuildSchedule(FileIndexItem item) {
    String execUrl =
          String.format("http://%s:%s/monitor/file/index/build/schedule/start", server, port);
    ResponseEntity<BaseResult> responseEntity = restTemplate
          .postForEntity(execUrl, item, BaseResult.class);
    return responseEntity.getBody();
  }

  public BaseResult stopFileIndexBuildSchedule(FileIndexItem item) {
    String execUrl =
          String.format("http://%s:%s/monitor/file/index/build/schedule/stop", server, port);
    ResponseEntity<BaseResult> responseEntity = restTemplate
          .postForEntity(execUrl, item, BaseResult.class);
    return responseEntity.getBody();
  }

  public BaseResult indexBuildOnce(FileIndexItem item) {
    String execUrl = String
          .format("http://%s:%s/monitor/file/index/build/once", server, port);
    ResponseEntity<BaseResult> responseEntity = restTemplate
          .postForEntity(execUrl, item, BaseResult.class);
    return responseEntity.getBody();
  }

  //数据完整性记录查询
  public BaseResult getIndexBuildStatus(List<String> ids) {
    String queryParam = String.join(",", ids);
    String execUrl = String.format(
          "http://%s:%s/monitor/file/index/build/status?ids=%s", server, port, queryParam);

    return restTemplate
          .getForEntity(execUrl, BaseResult.class)
          .getBody();
  }
}
